package com.fengba.nanzhi.tabbar01;

import android.app.Fragment;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.fengba.nanzhi.fengba.MainActivity;
import com.fengba.nanzhi.fengba.R;
import com.fengba.nanzhi.login.Login;
import com.fengba.nanzhi.utils.FX_SignInUtil;
import com.fengba.nanzhi.utils.Function;
import com.fengba.nanzhi.utils.MarginDecoration;
import com.fengba.nanzhi.utils.MarqueeView;
import com.fengba.nanzhi.utils.HeaderGridView;
import com.fengba.nanzhi.utils.OKManager;
import com.fengba.nanzhi.utils.Preferences;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


/**
 * Created by duan on 2018/4/1.
 */

public class Tabbar01 extends Fragment {
    private OKManager manager = OKManager.getInstance();
    private JSONArray jsonArray;
    private static ViewPager viewPager;
    private RadioGroup group;
    //图片资源，实际项目需要从网络获取
    //private int[] imageIds = {R.mipmap.img_0001,R.mipmap.img_0002};
    private String[] imageIds = {""};
    //存放图片的数组
    private List<ImageView> mList;
    //当前索引位置以及上一个索引位置
    private static int index = 0, preIndex = 0;
    //是否需要轮播标志
    private boolean isContinue = true;
    //定时器，用于实现轮播
    private Timer timer = new Timer();
    private MyHandler mHandler;

    private View self_view;

    private JSONArray jsonArray1;
    private Boolean flage = true;
    private View header;
    private RecyclerView recyclerView;
    private JSONArray jsonArray3;
    private int width;


    public static class MyHandler extends Handler {
        private WeakReference<MainActivity> weakReference;

        public MyHandler(MainActivity activity) {
            weakReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            if (weakReference.get() != null) {
                index++;
                viewPager.setCurrentItem(index);
            }
            super.handleMessage(msg);
        }
    }

    public static Tabbar01 newInstance(String param) {
        Tabbar01 tabbar01 = new Tabbar01();
        Bundle args = new Bundle();
        args.putString("agrs1", param);
        tabbar01.setArguments(args);
        return tabbar01;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        if (self_view != null) {
            return self_view;
        }
        View view = inflater.inflate(R.layout.tabbar01, container, false);

         recyclerView = (RecyclerView) view.findViewById(R.id.Ashdzlb);
        recyclerView.addItemDecoration(new MarginDecoration(getActivity()));
        recyclerView.setHasFixedSize(true);
        final GridLayoutManager manager = new GridLayoutManager(getActivity(), 2);
        recyclerView.setLayoutManager(manager);
        header = LayoutInflater.from(getActivity()).inflate(R.layout.fx_bena, recyclerView, false);
        final HeaderNumberedAdapter adapter = new HeaderNumberedAdapter(header, 0,getActivity(),null);
        recyclerView.setAdapter(adapter);
        manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                return adapter.isHeader(position) ? manager.getSpanCount() : 1;
            }
        });
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //int heigth = dm.heightPixels;
        width= dm.widthPixels;
        MarqueeView mMarquee1 = (MarqueeView) header.findViewById(R.id.mv_bar1);
        /**
         * 签到
         */
        ImageButton IB01 = (ImageButton) header.findViewById(R.id.IB01);
        IB01.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (FX_SignInUtil.switchAccount(getActivity())) {
                    startActivity(new Intent(getActivity(), Login.class));
                } else {
                    startActivity(new Intent(getActivity(), MultiChooseActivity.class));
                }
            }
        });
        /**
         * 兑换
         */
        ImageButton IB02 = (ImageButton) header.findViewById(R.id.IB02);
        IB02.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (FX_SignInUtil.switchAccount(getActivity())) {
                    startActivity(new Intent(getActivity(), Login.class));
                } else {
                    startActivity(new Intent(getActivity(), Exchange.class));
                }
            }
        });
        /**
         * 疯豆
         */
        ImageButton IB03 = (ImageButton) header.findViewById(R.id.IB03);
        IB03.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String account = null;
                try {
                    Object user_info = Preferences.getParam(getActivity(), "user_info", "");
                    JSONObject myJson = null;
                    myJson = new JSONObject(user_info.toString());
                    account = myJson.get("account").toString();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (FX_SignInUtil.switchAccount(getActivity())) {
                    startActivity(new Intent(getActivity(), Login.class));
                } else {
                    startActivity(new Intent(getActivity(), FX_FD.class));
                }
            }
        });
        self_view = view;
        final RefreshLayout refreshLayout = (RefreshLayout) view.findViewById(R.id.ArefreshLayout);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {

            public void onRefresh(RefreshLayout refreshlayout) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        init();
                        if (jsonArray1 == null) {
                            Toast.makeText(getActivity(), "已经没有更多数据了", Toast.LENGTH_SHORT).show();
                            refreshLayout.finishRefresh();
                        } else {
                            Toast.makeText(getActivity(), "刷新成功", Toast.LENGTH_SHORT).show();
                            refreshLayout.finishRefresh();
                        }
                        /**
                         * 刷新完成后调用此方法，要不然刷新效果不消失
                         */

                    }
                }, 0);
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                refreshlayout.finishLoadMore(2000/*,false*/);//传入false表示加载失败
            }
        });
        /**
         * 初始化控件
         */
        viewPager = (ViewPager) header.findViewById(R.id.viewPager);
        //group = (RadioGroup) view.findViewById(R.id.viewGroup);
        group = (RadioGroup) header.findViewById(R.id.viewGroup);
        initData();
        addListener();
        //让当前图片位于中间某个位置，目的就是为了开始能够左滑
        viewPager.setCurrentItem(imageIds.length * 100);
        startSwitch();
        init();
        return view;

    }

    /**
     * 初始化数据
     */
    public void initData() {
        mList = new ArrayList<>();
        viewPager.setAdapter(pagerAdapter);
        mHandler = new MyHandler(new MainActivity());
    }

    /**
     * 添加监听
     */
    public void addListener() {
        viewPager.addOnPageChangeListener(onPageChangeListener);
        viewPager.setOnTouchListener(onTouchListener);
    }

    /**
     * 进行图片轮播
     */
    public void startSwitch() {
        //执行定时任务
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                //首先判断是否需要轮播，是的话我们才发消息
                if (isContinue) {
                    mHandler.sendEmptyMessage(1);
                }
            }
        }, 3000, 3500);//延迟3秒，每隔3.5秒发一次消息;
    }

    /**
     * 根据图片个数初始化按钮
     *
     * @param length 图片所在集合长度
     */
    private void initRadioButton(int length) {
        for (int i = 0; i < length; i++) {
            ImageView imageview = new ImageView(getActivity());
            imageview.setImageResource(R.drawable.page_indicator_focused);//设置背景选择器
            imageview.setPadding(20, 0, 0, 20);//设置每个按钮之间的间距
            //将按钮依次添加到RadioGroup中
            group.addView(imageview, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            //默认选中第一个按钮，因为默认显示第一张图片
            //group.getChildAt(0).setEnabled(false);
            //group.getChildAt(0).setColorFilter();
            //group.getChildAt(0).getResources().getDrawable(R.mipmap.img_0002);
            ImageView imageviews = (ImageView) group.getChildAt(0);
            //group.getChildAt(i).setEnabled(false);//当前按钮选中,显示蓝色
            imageviews.setColorFilter(Color.WHITE);
        }
    }

    /**
     * 设置对应位置按钮的状态
     *
     * @param i 当前位置
     */
    private void setCurrentDot(int i) {
        if (group.getChildAt(i) != null) {
            ImageView imageview = (ImageView) group.getChildAt(i);
            //group.getChildAt(i).setEnabled(false);//当前按钮选中,显示蓝色
            imageview.setColorFilter(Color.WHITE);
        }
        if (group.getChildAt(preIndex) != null) {
            group.getChildAt(preIndex).setEnabled(true);//上一个取消选中。显示灰色
            ImageView imageview = (ImageView) group.getChildAt(preIndex);
            preIndex = i;//当前位置变为上一个，继续下次轮播
            imageview.setColorFilter(Color.BLACK);
        }
    }

    /**
     * 根据当前触摸事件判断是否要轮播
     */
    View.OnTouchListener onTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                //手指按下和划动的时候停止图片的轮播
                case MotionEvent.ACTION_DOWN:
                case MotionEvent.ACTION_MOVE:
                    isContinue = false;
                    break;
                default:
                    isContinue = true;
            }
            return false;//注意这里只能返回false,如果返回true，Dwon就会消费掉事件，MOVE无法获得事件，
            // 导致图片无法滑动
        }
    };
    /**
     * 根据当前选中的页面设置按钮的选中
     */
    ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            index = position;//当前位置赋值给索引
            setCurrentDot(index % imageIds.length);//因为只有四个按钮，所以我们在此要对长度区域，保证范围在0到4
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }
    };
    PagerAdapter pagerAdapter = new PagerAdapter() {
        @Override
        public int getCount() {
            //返回一个比较大的值，目的是为了实现无限轮播
            return Integer.MAX_VALUE;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            position = position % imageIds.length;//因为position非常大，而我们需要的position不能大于图片集合长度
            //所以在此取余
            ImageView imageView = new ImageView(getActivity());
            //imageView.setImageResource(imageIds[position]);
            if (imageView!=null) {
                Glide.with(getActivity()).load(imageIds[position].toString()).into(imageView);
            }
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            container.addView(imageView);
            mList.add(imageView);
            return imageView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
//         注意在此不要做任何操作，因为我们需要实现向左滑动，否则会产生IndexOutOfBoundsException
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        //页面销毁的时候取消定时器
        if (timer != null) {
            preIndex = 0;
            //timer.cancel();
        }
    }

    public void init() {
        manager.type2003(new OKManager.func4() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                try {
                    if (jsonObject.get("code").equals(0)) {
                        jsonArray = jsonObject.getJSONArray("data1");
                        jsonArray1 = jsonObject.getJSONArray("data");
                        ////System.out.println("jsonArray1"+jsonArray1.toString());
                        jsonArray3= jsonObject.getJSONArray("data2");
                        List<String> items_= new ArrayList<String>();
                        for (int i = 0; i < jsonArray3.length(); i++) {
                            JSONObject a = (JSONObject) jsonArray3.get(i);
                            items_.add("恭喜"+Function.phoneHide4Start(a.getString("mobile").toString())+"用户中了"+a.getString("goods_name").toString());
                        }
                        MarqueeView mMarquee1 = (MarqueeView) header.findViewById(R.id.mv_bar1);
                        //设置集合
                        mMarquee1.startWithList(items_);
                        mMarquee1.setOnItemClickListener(new MarqueeView.OnItemClickListener() {
                            @Override
                            public void onItemClick(int position, TextView textView) {
                                Toast.makeText(getActivity(), textView.getText().toString(), Toast.LENGTH_SHORT).show();
                            }
                        });
                        final GridLayoutManager manager = new GridLayoutManager(getActivity(), 2);
                        final HeaderNumberedAdapter adapter = new HeaderNumberedAdapter(header, 0,getActivity(),jsonArray1);
                        recyclerView.setAdapter(adapter);
                        manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                            @Override
                            public int getSpanSize(int position) {
                                return adapter.isHeader(position) ? manager.getSpanCount() : 1;
                            }
                        });
                        if (flage) {
                            int inSize = jsonArray.length() - 1;//增加的个数
                            String temp[] = new String[imageIds.length + inSize];//临时数组
                            imageIds = temp;
                            initRadioButton(jsonArray.length());//注意这句和上面那句顺序不能写反，否则会出现第一个圆点无法显示选中状态
                        }
                        flage = false;
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject a = (JSONObject) jsonArray.get(i);
                            imageIds[i] = a.get("images").toString();
                        }
                        /**
                         * 初始化控件
                         */
                        initData();
                    } else {
                        //Toast.makeText(getActivity(), jsonObject.get("message").toString(), Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(String string) {
                //Toast.makeText(getActivity(), "网络错误", Toast.LENGTH_SHORT).show();
            }
        });
    }

    public JSONArray getJsonArray() {
        return jsonArray1;
    }
    public int getwidth() {
        return width;
    }

}
